package com.njupt.user.webapp.action;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.StrutsRequestWrapper;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.njupt.blog.Constants;
import com.njupt.service.UniversalManager;
import com.njupt.system.model.UserAuthority;
import com.njupt.auth.service.UserDetailsService;
import com.njupt.auth.model.UserDetails;

public class AutoLoginFilter implements Filter
{

	public void init(FilterConfig arg0) throws ServletException
	{
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException
	{

		HttpServletRequest request = (HttpServletRequest) req;
		Cookie[] cookies = request.getCookies();
		String username = null;
		String password = null;

		if (request.getSession(true).getAttribute(
				Constants.SECURITY_CONTEXT_KEY) == null)
		{
			if (cookies != null)
			{
				String ctx = request.getContextPath();
				for (Cookie cookie : cookies)
				{
					if (cookie.getName().equals("username_" + ctx))
					{
						username = cookie.getValue();
						username = URLDecoder.decode(username, "utf-8");
					}

					if (cookie.getName().equals("password_" + ctx))
					{
						password = cookie.getValue();
						password = URLDecoder.decode(password, "utf-8");
					}
				}
				WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        		UserDetailsService userDetailsService = (UserDetailsService) wac.getBean("userDetailsService"); 
        		UserDetails u = userDetailsService.loadUserByUsername(username);

				if (u != null && u.getPassword().equals(password)
						&& u.isEnabled())
				{
					request.getSession().setAttribute(
							Constants.SECURITY_CONTEXT_KEY, u);
					UniversalManager manager = (UniversalManager) wac.getBean("manager");
					UserAuthority userAuthority = manager.findUniqueBy(UserAuthority.class, "username", username);
					request.getSession().setAttribute(
							Constants.SECURITY_CONTEXT_ROLE, userAuthority.getAuthority());
					request.getSession().setAttribute("currentUsername",
							username);
				}
			}
		}
		chain.doFilter(new StrutsRequestWrapper((HttpServletRequest) req), resp);
	}

	public void destroy()
	{
		// TODO Auto-generated method stub
	}

}
